<script setup>
import {ref, computed, reactive} from "vue";
import {useStore} from "vuex";
import {ElMessage, ElMessageBox} from "element-plus";


let store = useStore();
const input1 = ref('')
const dialogKey = ref(0);
const dialogFormVisible = ref(false);
let form = reactive({
  id: 0,
  name: '',
  password: '',
  otherName: '',
  mail: '',
  phone: '',
  role: null,
  del: false
});
const isDarkTheme = computed(() => store.state.theme === 'dark');

const roleMap = {
  1: '超级管理员',
  2: '专业咨询师',
  3: '普通用户'
};

const currentPage = ref(1);
const pageSize = ref(5); // 每页显示的条目数
const total = computed(() => store.state.userForm.length); // 总条目数

const value1 = ref('')

const userForm = computed(() => store.state.userForm)

const usersOnCurrentPage = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return store.state.userForm.slice(start, end);
});
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

const searchUsers = () => {
  const searchName = input1.value;
  const filteredUsers = store.state.userForm.filter(user => user.name.includes(searchName));
  const userStrings = filteredUsers.map(user => `ID: ${user.id}, 用户名: ${user.name}, 昵称: ${user.otherName}`).join('\n');

  ElMessageBox({
    title: '搜索结果',
    message: userStrings,
    dangerouslyUseHTMLString: true,
    beforeClose: (action, instance, done) => {
      // 可以在这里执行一些操作，例如清理数据
      done(); // 确保调用 done 以关闭对话框
    }
  });
};

const addUserDialog = () => {
  form = reactive({
    id: 0,
    name: '',
    password: '',
    otherName: '',
    mail: '',
    phone: '',
    role: null,
    del: false
  });
  dialogFormVisible.value = true;
};

const editUser = (user) => {
  Object.assign(form, { ...user }); // 将用户数据填充到表单
  dialogFormVisible.value = true; // 显示对话框
};

const submitUser = () => {
  if (form.id) {
    // 更新用户
    const index = store.state.userForm.findIndex(u => u.id === form.id);
    if (index !== -1) {
      store.commit('updateUser', {index, updatedUser: form});
    }
  } else {
    // 添加用户
    form.id = store.state.userForm.length + 1; // 确保在添加用户时生成ID
    store.commit('addUser', form);
  }
  ElMessage({
    type: 'success',
    message: form.id ? '用户更新成功' : '用户添加成功'
  });
  dialogFormVisible.value = false; // 关闭对话框
};

const handleCancel = () => {
  ElMessage({
    type: 'info',
    message: '取消操作'
  });
  dialogFormVisible.value = false;
};

const deleteUser = (user) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = store.state.userForm.findIndex(u => u.id === user.id);
    if (index !== -1) {
      store.commit('removeUser', index);
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除'
    });
  });
};


</script>

<template>
  <div>
    <div class="right-little-body">
      <div class="little-title">
        <div class="title-top">
          <div class="title-top-left">
            <span>用户名称：</span>
            <div style="display: inline-block">
              <el-input
                  v-model="input1"
                  style="width: 200px"
                  size="large"
                  placeholder=""
              />
            </div>
          </div>
          <div class="title-top-middle">
            <div class="demo-date-picker">
              <div class="block">
                <span class="demonstration">创建时间：</span>
                <el-date-picker
                    v-model="value1"
                    type="daterange"
                    range-separator="To"
                    start-placeholder="Start date"
                    end-placeholder="End date"
                    :size="'default'"
                />
              </div>
            </div>
          </div>
          <div class="title-top-right">
            <el-button type="primary" @click="searchUsers">搜索</el-button>
          </div>
        </div>
        <div class="title-middle">
          <el-button type="primary" @click="addUserDialog">新增</el-button>
        </div>
        <div class="title-bottom">
          <el-table :data="usersOnCurrentPage" stripe style="width: 1200px" :border="true">
            <el-table-column prop="id" label="编号" />
            <el-table-column prop="name" label="用户名"/>
            <el-table-column prop="password" label="密码"/>
            <el-table-column prop="otherName" label="昵称"/>
            <el-table-column prop="mail" label="邮箱"/>
            <el-table-column prop="phone" label="手机号"/>
            <el-table-column label="角色">
              <template #default="scope">
                <!-- 根据角色ID显示对应的角色名称 -->
                <span>{{ roleMap[scope.row.role] }}</span>
              </template>
            </el-table-column>
            <el-table-column label="编辑">
              <template #default="scope">
                <el-button type="primary" @click="editUser(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
            <el-table-column label="删除">
              <template #default="scope">
                <el-button type="danger" @click="deleteUser(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
                layout="prev, pager, next"
                :total="total"
                :page-size="pageSize"
                :current-page="currentPage"
                @current-change="handleCurrentChange"
            />
          </div>


        </div>
      </div>
      <div>
        <el-dialog
            v-model="dialogFormVisible"
            :key="dialogKey"
            title="用户信息"
            width="500px"
            @before-close="handleCancel">

          <el-form :model="form">
            <el-form-item label="用户名" :label-width="100">
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" :label-width="100">
              <el-input v-model="form.password" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="昵称" :label-width="100">
              <el-input v-model="form.otherName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" :label-width="100">
              <el-input v-model="form.mail" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号" :label-width="100">
              <el-input v-model="form.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色" :label-width="100">
              <el-select v-model="form.role" placeholder="请选择角色">
                <el-option label="超级管理员" value="1"></el-option>
                <el-option label="专业咨询师" value="2"></el-option>
                <el-option label="普通用户" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="submitUser">确定</el-button>
            </div>
          </template>
        </el-dialog>
      </div>


    </div>
  </div>
</template>

<style scoped>
.right-little-body {
  padding: 20px;
  width: 100%;
  position: relative;
  height: 100%;
}

.little-title {
  width: 100%;
  height: 100%;
  display: inline-block;
}

.title-top {
  width: 100%;
  height: 40px;
}

.title-top-left {
  display: inline-block;
}

.title-top-middle {
  margin: 0 15px;
  display: inline-block;
}

.title-top-right {
  display: inline-block;
}

.title-middle {
  margin: 10px 15px;
}

.title-bottom {
  margin: 15px 15px;
}
.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>